/*
 * Copyright (c) 2005-2006 Rincon Research Corporation
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * - Redistributions of source code must retain the above copyright
 *   notice, this list of conditions and the following disclaimer.
 * - Redistributions in binary form must reproduce the above copyright
 *   notice, this list of conditions and the following disclaimer in the
 *   documentation and/or other materials provided with the
 *   distribution.
 * - Neither the name of the Rincon Research Corporation nor the names of
 *   its contributors may be used to endorse or promote products derived
 *   from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
 * RINCON RESEARCH OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE
 */
 
#include "Timer.h"
#include "RssiToSerial.h"
#include "printf.h"
 
 /**
  * This is more of a general demonstration than a test.
  *
  * Install this application to one node, connected to the computer.
  * The node will measure the environmental RSSI from the CC2420 and
  * sending those readings over the serial port.
  *
  * Use the Java application to display the relative RSSI readings.
  *
  * @author Jared Hill
 * @date   23 March 2007
  */
 
module RssiToSerialP {
  uses {
    interface Leds;
    interface Boot;
    interface AMSend;
    interface SplitControl as AMControl;
    interface SplitControl as SerialControl;
    interface Packet;
    interface Read<uint16_t> as ReadRssi;
    interface CC2420Config as Config;
    interface Timer<TMilli> as MyTimer;
    interface Timer<TMilli> as SyncTimer;
    interface Timer<TMilli> as SampleTimer;
    interface Bcast;

  }
}
implementation {

  /******* Global Variables ****************/
  message_t packet;
  bool locked;
  uint32_t total;
  uint16_t largest;
  uint32_t read;
  uint32_t syncTime;
  uint32_t startTime;
  uint32_t endTime;
  int reading;
  uint8_t channel;
  uint32_t round;

  
  uint32_t samplingTime;
  uint32_t samplingPeriod;
  uint32_t samples;
  uint32_t guardTime;
  uint32_t oneChannelSyncTime;
  uint32_t timestamp[1000];
  int readi[1000];
  
  uint8_t startSample;
  uint8_t isSynced;

  uint32_t index;
  
  /******** Declare Tasks *******************/
  task void readRssi();
  task void sendSerialMsg();
  
  /************ Boot Events *****************/
  event void Boot.booted() {
    int i = 0;
    total = 0;
    largest = 0;
    read = 0;
    reading = 0;
    locked = FALSE;
    round = 0;

    samples = 1000;
    samplingPeriod = 2;
    samplingTime = (samplingPeriod+2) * samples;
    guardTime = 500;
    oneChannelSyncTime = 30;
    startSample = 0;
    isSynced = 0;

    index = 0;

    for(i=0;i<samples;i++){
    	timestamp[i]=0;
	readi[i]=0;
    }

    if(TOS_NODE_ID==0) {
    	channel = 10;
    }
    else{
    	channel = TOS_NODE_ID;
    }
    call Config.setChannel(channel);
    call AMControl.start();
  }

  /************ AMControl Events ******************/
  event void AMControl.startDone(error_t err) {
    if (err == SUCCESS) {
      call SerialControl.start();
    }
    else {
      call AMControl.start();
    }
  }

  event void AMControl.stopDone(error_t err) {
    // do nothing
  }

  
  /***************SerialControl Events*****************/
  event void SerialControl.startDone(error_t error){
    if (error == SUCCESS) {
		//printf("testing\n");
		//printfflush();
	    	if(TOS_NODE_ID==0){call SyncTimer.startOneShot(1024*5);}
    }
    else {
      call AMControl.start();
    }
  }
  
  event void SerialControl.stopDone(error_t error){
    //do nothing
  }
  
  /***************** AMSend Events ****************************/
  event void AMSend.sendDone(message_t* bufPtr, error_t error) {
    
    	uint16_t i = 0;

   	call Leds.led0Toggle();
	if(error!=SUCCESS){
		post sendSerialMsg();
	}
    	if (&packet == bufPtr) {
      		locked = FALSE;
		if(index<1002){
			index++;
			post sendSerialMsg();
		}
		else{
			index=0;	
			for(i=0;i<samples;i++){
				timestamp[i]=0;
				readi[i]=0;
			}
		}
	}
  }

  event void MyTimer.fired(){
  }  

  task void printTask(){
  	int i = 0;
	for(i=0;i<samples;i++){
		printf("%lu, %i\n",timestamp[i],readi[i]);
		printfflush();
	}
	printf("infoe,%lu,%lu\n", round, endTime);
	printfflush();
	for(i=0;i<samples;i++){
		timestamp[i]=0;
		readi[i]=0;
	}
  }
  
  /**************** ReadRssi Events *************************/
  event void ReadRssi.readDone(error_t result, uint16_t val ){

    uint8_t temp = 0;
    uint32_t yushu = 0;
    bool equall = FALSE;

    //call SampleTimer.startOneShot(samplingPeriod);
    read++;
    call SampleTimer.startOneShot(samplingPeriod);
    
    if(result != SUCCESS){
      //post readRssi();
      return;
    }

    temp = (uint8_t)(val+128);
    if(temp>127) {
    	reading = temp - 256 - 45;
    }
    else {
    	reading = temp -45;
    }
    //reading = temp;
    yushu = read % samples;

    if(yushu==0){
    	call SampleTimer.stop();
  	startSample = 0;
	endTime = call Bcast.getTime();
	round = read/samples;
	//printf("infoe,%lu,%lu\n", round, endTime);
	//printfflush();
    	readi[samples-1]=reading;
	timestamp[samples-1]=call Bcast.getTime();
	post sendSerialMsg();
    }
    else{
    	readi[yushu-1]=reading;
	timestamp[yushu-1]=call Bcast.getTime();
	//printf("%lu, %i\n",timestamp[yushu-1],readi[yushu-1]);
	//printfflush();
    }
  }

  
  /********************* Config Events *************************/
  event void Config.syncDone(error_t error){
  
  }
  
  event void SampleTimer.fired(){
    	if(startSample==0){
		isSynced = 0;
		startSample = 1;
		startTime = call Bcast.getTime();
    		//printf("infos,%lu, %lu\n",round, startTime);
    		//printfflush();
	}
	call Leds.led0Toggle();
	post readRssi();
  }
 
  event void Bcast.Synced(){
  	uint32_t tempTime = 0;
/*	if(startSample==1){
		call SampleTimer.stop();
	}
*/
	if(TOS_NODE_ID!=0 && isSynced==0){
		isSynced = 1;
		//calculate the start sampling time
		tempTime = (27-channel)*oneChannelSyncTime + guardTime;

  		call SampleTimer.startOneShot(tempTime);
    		syncTime = call Bcast.getTime();
	  	call Leds.led2Toggle();
    		//printf("infoc,%u, %lu\n",channel, syncTime);
    		//printfflush();
  	}
  }

  event void SyncTimer.fired(){
  	if(TOS_NODE_ID==0) {
	  call Leds.led2Toggle();
	  printf("channel %u\n",channel);
	  printfflush();
	  if(channel<25) {
   		call SyncTimer.startOneShot(oneChannelSyncTime);
    		
		call Config.setChannel(++channel);
		//call Config.setChannel(12);
		call Config.sync();
		
		call Bcast.startSync();
	  }
	  else if(channel==25) {
   		call SyncTimer.startOneShot(oneChannelSyncTime + samplingTime + 5*guardTime);
    		
		call Config.setChannel(++channel);
		call Config.sync();
		
		call Bcast.startSync();

		channel = 10;
		//call Config.setChannel(channel);
		//call Config.sync();
	  }
	}
  }

  /***************** TASKS *****************************/  
  task void readRssi(){
   
    if(call ReadRssi.read() != SUCCESS){
      post readRssi();
    }
  }
  
  task void sendSerialMsg(){
    if(locked){
      return;
    }
    else {
      rssi_serial_msg_t* rsm = (rssi_serial_msg_t*)call Packet.getPayload(&packet, sizeof(rssi_serial_msg_t));
      
      if (call Packet.maxPayloadLength() < sizeof(rssi_serial_msg_t)) {
	    return;
      }

	if(index==0){
		rsm->first32b = channel;
		rsm->second32b = syncTime;
	}
	if(index==1){
		rsm->first32b = round;
		rsm->second32b = startTime;
	}
	if(index>=2 && index<=1001){
		rsm->first32b = timestamp[index-2];
		rsm->second32b = readi[index-2];
	}
	if(index==1002){
		rsm->first32b = round;
		rsm->second32b = endTime;
	}

	rsm->channel = call Config.getChannel();
	if (call AMSend.send(AM_BROADCAST_ADDR, &packet, sizeof(rssi_serial_msg_t)) == SUCCESS) {
		locked = TRUE;
	}
    }
 
  }
}




